package com.cloud.common.baseHandler;

import com.cloud.common.response.ProException;
import com.cloud.common.response.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @YIKOUJING
 * @author LXY
 * @Description 全局返回值包装
 * @createDate 2022/4/16
 * @createTime 23:18
 */
@RestControllerAdvice
public class ResponsePackAdvice implements ResponseBodyAdvice {
    //该方法判断是否要进行beforeBodyWrite方法
    //true进行false不进行
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //对已经包装成Result类型的结果不需要再次进行包装
        return ! (methodParameter.getParameterType().equals(Result.class) || methodParameter.getParameterType().equals(String.class));
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(methodParameter.getParameterType().equals(String.class)){
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(Result.success(o));
            } catch (JsonProcessingException e) {
                throw new ProException("String类型返回值包装异常");
            }
        }
        return Result.success(o);
    }
}
